package officeboost.domain;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import officeboost.domain.equip_venue.Equipment;

@Stateless
public class EquipmentService {

    @PersistenceContext
    EntityManager em;
    @EJB
    LogMgr logger;

    // Create an equipment
    public void persist(Equipment equipment) {
        if (equipment == null) {
            return;           
        }
        if (find(equipment.getId()) != null) {
            logger.log("equipment:" + equipment.getId() + "主键重复！");
            return;
        }
        em.persist(equipment);
    }

    public void deleteById(String id) {
        Equipment equipment = find(id);
        if (equipment == null) {
            return;
        }
        delete(equipment);
    }

    // delete an equopment
    public void delete(Equipment equipment) {
        em.remove(equipment);
    }

    public Equipment find(String id) {
        return em.find(Equipment.class, id);
    }

    public List<Equipment> findAll() {
        Query query = em.createQuery("from Equipment e");
        List<Equipment> equipments = query.getResultList();
        if (equipments == null) {
            equipments = new ArrayList<>();
        }

        return equipments;
    }

    public boolean reserve(Equipment e, GregorianCalendar startTime, GregorianCalendar endTime) {
//	boolean result = e.reserve(startTime, endTime);
//	return result;
        return false;
    }

    public boolean cancelReserve(Equipment e, int id) {
//	boolean isCanceled = e.cancelReserve(id);
//	return isCanceled;
        return false;
    }
    
    public void use(String id) {
        Equipment equipment = find(id);
        if (equipment == null) {
            return;
        }
        equipment.setStatus("occupied");
        em.merge(equipment);
    }

    public void release(String id) {
        Equipment equipment = find(id);
        if (equipment == null) {
            return;
        }
        equipment.setStatus("availiable");
        em.merge(equipment);
    }
    
    
    

}
